package com.lmabbe.oauth.service;

import com.lmabbe.common.global.context.LmabbeMetadata;
import com.lmabbe.common.global.context.metadata.client.OauthClient;
import com.lmabbe.oauth.context.MyClientDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
 * @author lmabbe
 */
@Service
@Slf4j
public class ClientDetailsServiceImpl implements ClientDetailsService {

    @Autowired
    private LmabbeMetadata lmabbeMetadata;
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        List<OauthClient> oauthClients = lmabbeMetadata.currentTenantClient();
        Optional<OauthClient> first = oauthClients.stream().filter(s -> s.getClientKey().equals(clientId)).findFirst();
        if (!first.isPresent()) {
            throw new ClientRegistrationException(clientId + "非法的客户端");
        }
        return new MyClientDetails(first.get(), bCryptPasswordEncoder);
    }
}
